'use strict'

const Service = require('egg').Service

class ChatService extends Service {
    getUrlParams(url) {
        const _url = url.split('?')[1]
        const param = new URLSearchParams(_url)
        const sendId = param.get('sendId')
        const receiveId = param.get('receiveId')
        return { sendId, receiveId }
    }
    async insertMsg({ sendId, receiveId, msg }) {
        const { model } = this.ctx
        const t = await model.transaction()
        try {
            const chatDate = new Date()
            await model.Chat.create(
                {
                    sendId,
                    receiveId,
                    msg,
                    chatDate,
                },
                { transaction: t }
            )
            await t.commit()
            return { sendId, receiveId, msg, chatDate }
        } catch (e) {
            console.log(e)
            await t.rollback()
            return false
        }
    }
    async getMsg(sendId, receiveId) {
        return await this.ctx.model.Chat.find({ where: { sendId, receiveId }, limit: 10, order: 'chatDate desc' })
    }
}

module.exports = ChatService
